package hu.mapro.gwtui.client.model;


public class MetaBase<R, T, V, P extends Property<T, V>> implements AccessibleProperty<R, T, V> {

	AccessibleProperty<R, ?, T> route;
	P property;
	
	public MetaBase(AccessibleProperty<R, ?, T> route, P property) {
		super();
		this.route = route;
		this.property = property;
	}

	private String label;
	private String path;
	
	public String getLabel() {
		if (label==null) {
			StringBuffer sb = new StringBuffer();
			createLabel(route, property, sb);
			label = sb.toString();
		}
		return label;
	}

	private static <R2, X2, T2, V2> void createLabel(AccessibleProperty<R2, X2, T2> route2,
			Property<T2, V2> property2, StringBuffer sb) {
		if (route2!=null) {
			createLabel(route2.getRoute(), route2.getProperty(), sb);
			sb.append(" > ");
		}
		sb.append(property2.getLabel());
	}

	public String getPath() {
		if (path==null) {
			StringBuffer sb = new StringBuffer();
			createPath(route, property, sb);
			path = sb.toString();
		}
		return path;
	}

	protected static <R2, X2, T2, V2> void createPath(AccessibleProperty<R2, X2, T2> route2,
			Property<T2, V2> property2, StringBuffer sb) {
		if (route2!=null) {
			createPath(route2.getRoute(), route2.getProperty(), sb);
			sb.append(".");
		}
		sb.append(property2.getPropertyName());
	}

	@Override
	public AccessibleProperty<R, ?, T> getRoute() {
		return route;
	}

	public V get(R object) {
		return get(object, route, property);
	}

	@SuppressWarnings("unchecked")
	static <R2, X2, T2, V2> V2 get(R2 object, AccessibleProperty<R2, X2, T2> route2,
			Property<T2, V2> property2) {
		T2 x;
		if (route2!=null) {
			x = get(object, route2.getRoute(), route2.getProperty());
		} else {
			x = (T2) object;
		}
		if (x==null) return null;
		return property2.get(x);
	}
	
	
	@Override
	public Property<T, V> getProperty() {
		return property;
	}

}
